/**
 * 
 */
package com.zufangbao.earth.handler.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.demo2do.core.entity.Result;
import com.zufangbao.earth.handler.OpenApiHandler;
import com.zufangbao.earth.handler.RentNotifyHandler;
import com.zufangbao.gluon.exception.CommonException;
import com.zufangbao.gluon.opensdk.AesUtil;
import com.zufangbao.gluon.opensdk.SignatureUtilsForPartner;
import com.zufangbao.gluon.spec.earth.GlobalSpec4Earth;
import com.zufangbao.gluon.spec.global.GlobalCodeSpec;
import com.zufangbao.gluon.spec.global.GlobalSpec;
import com.zufangbao.sun.entity.company.corp.App;
import com.zufangbao.sun.entity.customer.Customer;
import com.zufangbao.sun.entity.order.Order;
import com.zufangbao.sun.entity.sms.AppSmsConfig;
import com.zufangbao.sun.handler.SmsHandler;
import com.zufangbao.sun.service.AppService;
import com.zufangbao.sun.service.AppSmsConfigService;
import com.zufangbao.sun.service.CustomerService;
import com.zufangbao.sun.service.OrderService;

/**
 * @author wukai
 *
 */
@Component("rentNotifyHandler")
public class RentNotifyHandlerImpl implements RentNotifyHandler {
	
	@Autowired
	private OpenApiHandler openApiHandler;

	@Autowired
	private AppService appService;
	
	@Autowired
	private AppSmsConfigService appSmsConfigService;
	
	@Autowired 
	@Qualifier("ChanZuoSmsHandler")
	private SmsHandler smsHandler;
	
	private static final Log logger = LogFactory.getLog(RentNotifyHandlerImpl.class);
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private CustomerService customerService;
	
	@Value("#{config['app.home']}")
	private String appHome;
	
	@Override
	public void sendSms4NotifyPayRent(Date today) {
		
		logger.info("begin to load app");
	
		List<App> appList = appService.loadAll(App.class);
		
		for(App app : appList){
			
			AppSmsConfig appSmsConfig = appSmsConfigService.getSmsConfig4App(app);
			
			if(null != appSmsConfig){
				
				logger.info("begin to get app sms config["+appSmsConfig.toString()+"]");
				
				String notifyDateStr = appSmsConfig.getNotifyDateArray();
				
				logger.info("get the notifyDateStr["+notifyDateStr+"]");
				
				if(StringUtils.isEmpty(notifyDateStr)){
					
					logger.error("get notify date str error,notifyDateStr is empty for app["+app.getAppId()+"]");
					
					continue;
				}
				
				List<Integer> notifyDateList = new ArrayList<Integer>();
				
				for(String date : notifyDateStr.split(",")){
					
					notifyDateList.add(Integer.parseInt(date));
				}
				
				logger.info("begin to get need to notify order list");
				
				List<Order> orderList = orderService.getNeedNotifyOrder(app.getAppId(), notifyDateList, today);
				
				if(CollectionUtils.isEmpty(orderList)){
					
					continue;
				}
				
				for(Order order : orderList){
					
						if(null == order){
							
							continue;
						}
						sendSms4NotifyPayRent(order, appSmsConfig);
				}
				
			}
		}
		
	}

	@Override
	public boolean sendSms4NotifyPayRent(Order order,AppSmsConfig appSmsConfig){
		
		try {
			Customer customer = order.getCustomer();
			
			App app = customer.getApp();
			
			String customerName = customer.getName(),mobile = customer.getMobile(),totalRent = order.getTotalRent().toString();
			
			Long customerId = customer.getId();
			
			String smsContent = null;
			
			if(appSmsConfig.isNeedLink()){
				
				String link = null;
				
				try {
					link = createRentNotifyShortLink(customerId, order.generateUniqueBillId());
					
				} catch (CommonException e) {
					
					e.printStackTrace();
					
					logger.error("create short link error");
				}
				
				smsContent = String.format(appSmsConfig.getSmsTemplate(),app.getName(),customerName,totalRent,link);
				
			}else{
				
				smsContent = String.format(appSmsConfig.getSmsTemplate(),app.getName(),customerName,totalRent);
				
			}
			
			logger.info("get the sms content["+smsContent+"],with parma customerName["+customerName+"],mobile["+mobile+"],totalRent["+totalRent+"]");
			
			Result result = smsHandler.sendSms(mobile, smsContent);
			
			logger.info("end to send sms["+result.getCode()+"]");
			
			return result.getCode().equals(String.valueOf(GlobalCodeSpec.CODE_SUC));
			
		} catch (Exception e) {
		
			logger.error("send sms occur error["+e.getMessage()+"]");
			
			return false;
		}
	}
	public String createRentNotifyShortLink(Long customerId, String unqiueBillId) throws CommonException {
		
		try {
			Customer customer = customerService.load(Customer.class, customerId);
			
			if(null == customer){
				
				throw new CommonException(GlobalCodeSpec.GeneralErrorCode.ERROR_ILLEGAL_PARAM);
			}
			
			App app = customer.getApp();
			
			Map<String,Object> map = SignatureUtilsForPartner.convertEnterAppHomeParam2Map(app.getAppId(), app.getAppSecret(), customerId.toString());
			
			String signature = SignatureUtilsForPartner.makeMD5Signature(map);
			
			logger.info("encrypt params customerId["+customerId+"],unqiueBillId["+unqiueBillId+"]");
			
			StringBuffer params  = new StringBuffer(app.getAppId())
																.append(GlobalSpec.SPLIT_CHAR)
																.append(customerId).append(GlobalSpec.SPLIT_CHAR).append(unqiueBillId)
																.append(GlobalSpec.SPLIT_CHAR).append(signature);
			
			String longUrl = appHome + "/" + AesUtil.encrypt(params.toString(), GlobalSpec4Earth.ENCRYPT_SALT_STR);
			
			String shortUrl = openApiHandler.createShortUrl(longUrl);
			
			if(StringUtils.isEmpty(shortUrl)){
				
				return longUrl;
			}
			return shortUrl;
			
		} catch (Exception e) {
			
			throw new CommonException(GlobalCodeSpec.GeneralErrorCode.ERROR_SYSTEM);
		}
	}

}
